const mongoose = require('mongoose');
const News = require('../models/news.models');
const Comment = require('../models/comment.models');
var multiparty = require('multiparty');
var fs = require('fs');


exports.create = function (req,res,next) {
    const news = new News(req.body);
    news.save().then(data=>{
        res.json(data);
    });
};

exports.get = function (req,res,next) {
  const id = req.params.id;
  News.findById(id,function(err,result){
    res.json(result);
  })
};

exports.update = function (req,res,next) {
  const id = req.params.id;
  News.findByIdAndUpdate(id,{ $set:req.body },{ new:false }).then(data=>{
    res.json(data);//data:更新之前的数据
  })
};

exports.delete = function (req,res,next) {
  const id = req.params.id;
  News.findByIdAndRemove(id,function(err,doc){
    removeCommentByNewsIds([id]).then(val => {
      res.json({message:'新闻删除成功',status:200});
    });
  })
};

exports.removes = function (req, res, next) {
  const ids = req.body.ids.split(',');//将id拆分成数组
  if (ids.length > 0) {
    News.remove({ _id: { $in: ids } }).then(data => {
      removeCommentByNewsIds(ids).then(val => {
        res.json({message:'新闻删除成功',status:200});
      });
      
    });
  }
}

exports.list = function (req,res,next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 5;
  var quertCondition = {};

  if(req.body.cateid && req.body.cateid.trim().length > 0){
    var cateid = req.body.cateid;
    var paths = req.body.paths;
   
    if(paths.indexOf(cateid)){
      quertCondition={
        path: new RegExp(cateid,'g')
      };
    }
    
  };

  if(req.body.title && req.body.title.trim().length > 0){
    quertCondition = Object.assign(quertCondition,{
      title : new RegExp(req.body.title,'i')
    });
  };
  
  News.paginate(quertCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};

//根据newsIds删除评论
function removeCommentByNewsIds(ids) {
  return new Promise(resolve => {
    Comment.remove({newsId:{$in:ids}},function(err,result) {
      resolve(result)
    });
  });
}